package com.apes.fn.fico.reimbursement.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.hr.base.model.WorkPost;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.DutyCenter;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 费用借支表
 * Created by lishikun on 2021/1/26 17:54
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicUpdate
@DynamicInsert
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ExpenseDebit.CONST_TABLE_NAME)
public class ExpenseDebit extends Model {
    public static final String CONST_TABLE_NAME = "fn_expense_debit";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "费用借支表", padding = 5, prefix = "FJ%(company)%(yy)%(month)", useDateRange = true)
    @Comment("费用借支编码")
    private String id;
//
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "cost_center_id", referencedColumnName = "id")
//    @Comment("报销部门")
//    private DutyCenter dutyCenter;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private PartyRole company;

    @Comment("部门")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    private Dept dept;

    @Name
    @Comment("费用类别")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fee_type_id", referencedColumnName = "id")
    private Enumeration feeType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id", referencedColumnName = "id", nullable = false)
    @Comment("创建人岗位")
    private WorkPost workPost;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "borrower", referencedColumnName = "id")
    @Comment("借支人")
    private PartyRole borrower;

    @Comment("账户名称")
    @Column(name = "account_name")
    private String accountName;

    @Comment("账号")
    @Column(name = "account_number")
    private String accountNumber;

    @Comment("开户行")
    @Column(name = "account_bank")
    private String accountBank;

    @Comment("支行")
    @Column(name = "subbranch", length = 200)
    private String subbranch;


    @Comment("借支原因")
    @Column(name = "reason", length = 120)
    private String reason;

    @Comment("备注")
    @Column(name = "remark", length = 120)
    private String remark;

    @States(name = "订单状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "approve", name = "审核"),
            @State(id = "finish", name = "完成"),
            @State(id = "repeal", name = "终止"),
            @State(id = "delete", name = "删除"),
            @State(id = "cashier", name = "待付款"),
            @State(id = "repayment", name = "待还款")
    })
    @Column(name = "state", length = 10, nullable = false)
    private String state;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_id", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteId;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveId;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "repeal_id", referencedColumnName = "id")
    @Comment("终止人")
    private PartyRole repealId;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "repeal_date")
    @Comment("终止日期")
    private Date repealDate;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "pay_id", referencedColumnName = "id")
    @Comment("付款人")
    private PartyRole payId;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "pay_date")
    @Comment("付款日期")
    private Date payDate;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "repayment_date")
    @Comment("审核完成日期")
    private Date repaymentDate;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "finish_date")
    @Comment("完成日期")
    private Date finishDate;

    @Comment("付款回执文件")
    @Column(name = "upload", length = 4000)
    private String upload;


    @Comment("费用借支明细")
    @OneToMany(mappedBy = "expenseDebit", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<ExpenseDebitItem> expenseDebitItems = new ArrayList<>();

    @Comment("费用还款明细")
    @OneToMany(mappedBy = "expenseDebit", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<ExpenseRepaymentItem> expenseRepaymentItems = new ArrayList<>();

    @Comment("借支总金额")
    @Column(name = "expense_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double expenseDebitSum = 0.0;

    @Comment("还款总金额")
    @Column(name = "expense_repayment", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double expenseRepaymentSum = 0.0d;

    @Comment("冻结金额")
    @Column(name = "frozen_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double frozenAmount = 0.0d;

    @Transient // 待还金额
    private double pendingSum = 0.0d;

    @Comment("OA发起人")
    @Column(name = "OASponsor", length = 120)
    private String OASponsor;

    @Comment("控制父类审批")
    @Column(name = "need_Supper_OA")
    private String needSupperOA;

    @Transient
    private String feeTypeName;  // OA使用费用类型名称

    public String getFeeTypeName() {
        return feeType.getDescription();
    }

    // 获取费用还款明细
    public List<ExpenseDebitItem> getExpenseDebitItems() {
        for (ExpenseDebitItem item : expenseDebitItems) {
            item.setExpenseDebit(this);
        }
        return expenseDebitItems;
    }

    // 设置费用还款明细
    public void setExpenseDebitItems(List<ExpenseDebitItem> expenseDebitItems) {
        if (Objects.isNull(expenseDebitItems)) expenseDebitItems = new ArrayList<>();
        this.expenseDebitItems.clear();
        this.expenseDebitItems = expenseDebitItems;
    }


    // 获取费用还款明细
    public List<ExpenseRepaymentItem> getExpenseRepaymentItems() {
        for (ExpenseRepaymentItem item : expenseRepaymentItems) {
            item.setExpenseDebit(this);
        }
        return expenseRepaymentItems;
    }

    // 设置费用还款明细
    public void setExpenseRepaymentItems(List<ExpenseRepaymentItem> expenseRepaymentItems) {
        if (Objects.isNull(expenseRepaymentItems)) expenseRepaymentItems = new ArrayList<>();
        this.expenseRepaymentItems.clear();
        this.expenseRepaymentItems = expenseRepaymentItems;
    }

    //
//
//    // 获取费用还款总金额
//    @Transient
//    public double getExpenseRepaymentSum() {
//        if (expenseRepaymentItems != null && expenseRepaymentItems.size() != 0 ) {
//            return expenseRepaymentItems.stream().mapToDouble(ExpenseRepaymentItem::getRepaymentMoney).sum();
//        } else
//            return 0.0d;
//    }
    // 获取待还款金额
    @Transient
    public double getPendingSum() {
        return Arith.sub(expenseDebitSum, Arith.add(Arith.add(expenseRepaymentSum, expenseDebitItems.stream().map(ExpenseDebitItem::getCancelAmount).reduce(Arith::add).orElse(0.0)), frozenAmount));
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    @Comment("各类费用主管")
    @Column(name = "candidates", length = 300)
    private String candidates;


    @Comment("银行流水明细")
    @OneToMany(mappedBy = "expenseDebit", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<TransactionFlowItem> transactionFlowItems = new ArrayList<>();

    public List<TransactionFlowItem> getTransactionFlowItems() {
        for (TransactionFlowItem item : transactionFlowItems) {
            item.setExpenseDebit(this);
        }
        return transactionFlowItems;
    }

    @Column(name = "pay_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("付款金额")
    private double payAmount = 0;

    /**
     * 计算金额
     */
    public void computeAmt() {
        payAmount = transactionFlowItems.stream().map(TransactionFlowItem::getPayAmount).reduce(Arith::add).orElse(0.0);
        expenseDebitSum = expenseDebitItems.stream().map(ExpenseDebitItem::getExpenseAmount).reduce(Arith::add).orElse(0.0);
        expenseRepaymentSum = expenseDebitItems.stream().map(ExpenseDebitItem::getRepaymentAmount).reduce(Arith::add).orElse(0.0);
        frozenAmount = expenseDebitItems.stream().map(ExpenseDebitItem::getFreezeAmount).reduce(Arith::add).orElse(0.0);
        if (payAmount > expenseDebitSum) {
            throw new RuntimeException("付款金额大于借支金额！请检查！");
        }

        if (Arith.add(expenseRepaymentSum, frozenAmount) > expenseDebitSum) {
            throw new RuntimeException("还款金额+还款冻结金额大于借支金额！请检查！");
        }
    }

    /**
     * 判断还款状态
     */
    public void computeState(){
        if (expenseDebitSum==Arith.add(expenseRepaymentSum, expenseDebitItems.stream().map(ExpenseDebitItem::getCancelAmount).reduce(Arith::add).orElse(0.0))){
            state = "finish";
        }
    }
}
